package model

import (
	"fmt"
	"time"
	"webstack/config"

	"github.com/things-go/gormzap"

	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// db 数据库
var db *gorm.DB

func init() {
	var (
		err error
	)

	// TODO: 数据库不存在则创建
	createDatabase()

	newLogger := gormzap.New(config.Logger,
		gormzap.WithConfig(logger.Config{
			SlowThreshold:             200 * time.Millisecond,
			Colorful:                  false,
			IgnoreRecordNotFoundError: false,
			LogLevel:                  logger.Info,
		}),
	)

	ormConfig := &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
		SkipDefaultTransaction:                   true,
		Logger:                                   newLogger,
	}

	var uri string
	if config.DatabaseType == "mysql" {
		uri = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", config.MysqlUser, config.MysqlPass, config.MysqlHost, config.MysqlPort, config.MysqlName)
		db, err = gorm.Open(mysql.Open(uri), ormConfig)
	} else if config.DatabaseType == "postgresql" {
		uri = fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Shanghai", config.PostgresqlHost, config.PostgresqlUser, config.PostgresqlPass, config.PostgresqlName, config.PostgresqlPort)
		db, err = gorm.Open(postgres.Open(uri), ormConfig)
	} else {
		db, err = gorm.Open(sqlite.Open("database.db"), ormConfig)
	}

	if err != nil {
		config.Logger.Error(uri)
		panic(fmt.Sprintf("链接数据库失败:%v\n", err))
	}

	db.AutoMigrate(&Web{}, &WebCategory{}, &SearchEngines{}, &SearchEnginesCategory{})
}

func createDatabase() {
	var my *gorm.DB
	var err error
	if config.DatabaseType == "mysql" {
		my, err = gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", config.MysqlUser, config.MysqlPass, config.MysqlHost, config.MysqlPort, config.MysqlName)), &gorm.Config{})
		if err != nil {
			my.Exec("CREATE DATABASE IF NOT EXISTS " + config.MysqlName)
		}
	} else if config.DatabaseType == "postgresql" {
		my, err = gorm.Open(postgres.Open(fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Shanghai", config.PostgresqlHost, config.PostgresqlUser, config.PostgresqlPass, config.PostgresqlName, config.PostgresqlPort)), &gorm.Config{})
		if err != nil {
			my.Exec("CREATE DATABASE IF NOT EXISTS " + config.PostgresqlName)
		}
	}
}
